import captchapng from 'typed-captchapng';
import crypto from '../util/crypto';
import { jwtSecretMd5 } from '../config';
import { formatReqLog } from '../util/';
import http from 'request';
const Captchapng = captchapng;

// 接口uuid设置,验证码（req接收,res响应）
const captcha = async (req: any, res: any) => {
  const num = req.query.uuid?.replace(/[^0-9]/ig, '');
  const index = Array.from({ length: 4 }, () => Math.floor(Math.random() * 10));
  let uuid = '';
  index.forEach(i => {
    uuid += num?.substr(i, 1) || '0';
  });
  if (uuid) {
    const code = await new Captchapng(100, 30, Number(uuid));
    const img = code.getBase64();
    const imgbase64 = Buffer.from(img, 'base64');
    res.header('Content-Type', 'image/png');
    res.setHeader('Set-Cookie', [
      `captchaCode=${crypto.encrypt(uuid)};path=/;httpOnly;max-age=360;`,
      `loginEncryptionKey=${jwtSecretMd5};path=/;max-age=360;`
    ]);
    res.end(imgbase64);
  } else {
    res.send(formatReqLog(400, '传入的uuid有误', null, { goal: req.originalUrl }));
  }
};

const weather = async (req: any, res: any) => {
  const token = '6070b79aa5bb22455af18ac2f26ba9fe';
  const city = req.query.city || '430181'; // 浏阳市
  await http({
    url: 'https://restapi.amap.com/v3/weather/weatherInfo',
    method: 'get',
    qs: { // form data
      city,
      key: token,
      extensions: 'base' // base: 返回实况天气 all: 返回预报天气
    }
  }, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      const data = JSON.parse(body);
      const lives = data.lives[0];
      http({
        url: 'https://restapi.amap.com/v3/weather/weatherInfo',
        method: 'get',
        qs: {
          city,
          key: token,
          extensions: 'all'
        }
      }, (error, response, body) => {
        if (!error && response.statusCode === 200) {
          const data = JSON.parse(body);
          res.send(formatReqLog(200, data.info, { lives, forecasts: data.forecasts[0] }, { goal: req.originalUrl, total: data.count }));
        }
      });
    } else {
      res.send(formatReqLog(300, 'weather', error, { goal: req.originalUrl }));
    }
  });
};

export = {
  captcha,
  weather
};
